var geocoder;
var map;
var lat = null;
var lng = null;

$(window).on('pagechange', function(event, data) {
	initialize();
});
function initialize() {

	var w = $(window).width();
	var h = $(window).height();
	$("#map-canvas").width(w);
	$("#map-canvas").height(h);
	geocoder = new google.maps.Geocoder();
	var lat = parseFloat($('#latitud').val());
	var lng = parseFloat($('#longitud').val());

	var latLng;
	if (lat != '' && lng != '') {

		latLng = new google.maps.LatLng(lat, lng);
	} else {
		latLng = new google.maps.LatLng(37.0625, -95.677068);
	}
	var mapOptions = {
		zoom : 14,
		center : latLng,
		rotateControl : true
	};
	var map = new google.maps.Map(document.getElementById('map-canvas'),
			mapOptions);
	new google.maps.Marker({
		map : map,
		position : latLng
	});
	google.maps.event.addDomListener(window, "resize", function() {

		var center = map.getCenter();
		var w = $(window).width();
		var h = $(window).height();
		$("#map-canvas").width(w);
		$("#map-canvas").height(h);
		google.maps.event.trigger(map, "resize");
		map.setCenter(center);
	});
}
function codeAddress() {
	var address = document.getElementById('direccion').value;
	address = address + ", " + $("#comuna").val() + ", chile ";
	geocoder.geocode({
		'address' : address
	},
			function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {

					map.setCenter(results[0].geometry.location);

					var marker = new google.maps.Marker({
						map : map,
						position : results[0].geometry.location
					});
					updatePosition(results[0].geometry.location);

					google.maps.event.addListener(marker, 'dragend',
							function() {
								updatePosition(marker.getPosition());
							});
				} else {

					alert("No podemos encontrar la direcci&oacute;n, error: "
							+ status);
				}
			});
}
function updatePosition(latLng) {

	$('#latitud').val(latLng.lat());
	$('#longitud').val(latLng.lng());

}